package cn.zhejianglao.oss.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.zhejianglao.oss.constants.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class PreInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    // 在 WebMvcConfigurer 中进行注入
    public PreInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取 Token (email)
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            // 没有 Token 输入, 直接放行
            return true;
        }
        String key = RedisConstants.USER_LOGIN_TOKEN_PREFIX + token;
        // 判断是否存在
        if (stringRedisTemplate.opsForValue().get(key) != null) {
            stringRedisTemplate.expire(key, 30, TimeUnit.MINUTES);
        }


        // 4. 放行
        return true;
    }
}
